import java.util.regex.*;
import java.io.*;
final class XmlFileRegex{
	public static StringBuffer replaceTagAttr(StringBuffer fileContent,
	String tag,String attr,String pattern, String value) 
	throws IOException{
		StringBuffer sb=new StringBuffer(fileContent.length());
		int count=0;
		Matcher m=Pattern.compile("<"
			+tag
			+"((<%([\\s\\S](?!%>))+[\\s\\S]%>|[^>])+)>",
			Pattern.MULTILINE
		).matcher(fileContent);
		while(m.find()){
			String text=m.group(1);
			StringBuffer sb2=new StringBuffer(text.length());
			Matcher m2=Pattern.compile("\\s"
				+attr
				+"\\s*=\\s*(\"(<%([\\s\\S](?!%>))+[\\s\\S]%>|[^\"])+\"|'(<%([\\s\\S](?!%>))+[\\s\\S]%>|[^\"])+'|(<%([\\s\\S](?!%>))+[\\s\\S]%>|[^\\s])+)",
				Pattern.MULTILINE
				).matcher(text);
			while(m2.find()){
				String text2=Pattern.compile(
					pattern,Pattern.MULTILINE
				).matcher(
					m2.group(1)
				).replaceAll(value);
				m2.appendReplacement(
					sb2,
					Matcher.quoteReplacement(
						" "+attr+"="+text2
				));
			}
			m2.appendTail(sb2);
			m.appendReplacement(
				sb,
				Matcher.quoteReplacement(
					"<"+tag+sb2+">"
			));
			System.out.println((++count)+"=>"+"<"+tag+sb2+">");
		}
		m.appendTail(sb);
		return sb;
	}
	public static void updateTagAttr(String file,FileEncrypt encoding,
	String tag,String attr,String pattern, String value,
	boolean useBOM) throws IOException{
		FileUtil.write(file,
			replaceTagAttr(
				FileUtil.readAll(file,encoding),tag,attr,pattern,value
			),
			 encoding,
			 useBOM
		);
	}
	public static void updateTagAttr(String file,FileEncrypt encoding,
	String tag,String attr,String pattern, String value) 
	throws IOException{
		updateTagAttr(file, encoding, tag, attr, pattern, value,true);
	}
	public static void main(String args[]) throws IOException{
		if(args.length>0){
			FileEncrypt type=FileUtil.checkType(args[0]);
			if(type==FileEncrypt.UTF_8 || type==FileEncrypt.NO_BOM){
				boolean useBOM=type.equals("NO BOM");
				XmlFileRegex.updateTagAttr(
					args[0],
					FileEncrypt.UTF_8,
					"script",
					"src",
					"([\"\']?)(.*\\.(js|asp)).*\\1$",
					"$1$2?ver=<%=Replace(Mid(\"\\$Date\\$\",8,10),\"/\",\"\")%>$1",
					useBOM
				);
			}else
				System.err.println(type+" is not supported!");
		}
	}
}
